package com.example.sunsg.okhttptest.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;

/**
 * Created by sunsg on 16/1/13.
 */
public class HorizenScrollView extends ViewGroup{
    private int mTouchSlop;
    /**子view宽*/
    private int mChildWidth;

    /**index*/
    private int mIndex;

    /**拦截*/
    private int xLastInterce;
    /**拦截*/
    private int yLastInterce;

    private int xLast;
    private int yLast;
    private Scroller mScroller;
    private VelocityTracker mVelocityTracker;
    private int xDown;
    public HorizenScrollView(Context context) {
        this(context,null);
    }

    public HorizenScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context){
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mScroller = new Scroller(context,new DecelerateInterpolator());
        mVelocityTracker = VelocityTracker.obtain();
    }


    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean isInter = false;
         int tempX = (int)ev.getX();
         int tempY = (int)ev.getY();
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                xLastInterce = tempX;
                yLastInterce = tempY;
                xLast = tempX;
                yLast = tempY;
                xDown = tempX;
                Log.i("test","inter down");
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = Math.abs(tempX - xLastInterce);
                float dy = Math.abs(tempY - yLastInterce);
//                Log.i("test","dx = "+dx);
//                Log.i("test","dy = "+dy);
                if(dy - dx > 0){
//                    if(mTouchSlop < dx){
                        isInter = false;
//                    }
                }else{
                    isInter = true;
                }
                xLastInterce = tempX;
                yLastInterce = tempY;
//                Log.i("test","move = isInter = "+isInter);
                Log.i("test","inter move");
                break;

            case MotionEvent.ACTION_UP:
                isInter = false;
//                Log.i("test","inter up");
                break;

        }
//        Log.i("test","isInter = "+isInter);
        return isInter;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mVelocityTracker.addMovement(event);
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                if(!mScroller.isFinished()){
                    mScroller.abortAnimation();
                }
                xLast = x;
                yLast = y;
                xDown = x;
                Log.i("test","down ==== "+xDown);
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = x - xLast;
                if(getScrollX() >=0 && getScrollX() <= getWidth() - mChildWidth){
                    scrollBy(-dx,0);

                    if(getScrollX() < 0){
                        setScrollX(0);
                    }
                    if(getScrollX() > getWidth() - mChildWidth){
                        setScrollX(getWidth() - mChildWidth);
                    }
                }
                xLast = x;
                yLast = y;
                break;
            case MotionEvent.ACTION_UP:
                int scrollx = getScrollX();
//                int index = scrollx/mChildWidth;
//                mIndex = index;
                mVelocityTracker.computeCurrentVelocity(1000);
                float xVelocity = mVelocityTracker.getXVelocity();
//                if (Math.abs(xVelocity) >= 50) {
//                    mIndex = xVelocity > 0 ? mIndex - 1 : mIndex + 1;
//                } else {
                    int dxMove = Math.abs(x - xDown);
                    int canChangeIndex = mChildWidth/3;
                    Log.i("test","x = "+x +" xDown = "+xDown + " dxMove ="+dxMove + " width/2 = "+mChildWidth/2);
                    if(dxMove > canChangeIndex){
                        if(x - xDown >0){
                            mIndex--;
                        }else{
                            mIndex++;
                        }
                    }

//                    mIndex = (scrollx + mChildWidth / 2) / mChildWidth;
//                }
                mIndex = Math.max(0, Math.min(mIndex, getChildCount() - 1));
                int dxx = mIndex * mChildWidth - scrollx;
                smoothScrollBy(dxx, 0);
                mVelocityTracker.clear();
                break;
        }
//        Log.i("test","scroll x = "+getScrollX() +" getwidth = "+getWidth());
        return super.onTouchEvent(event);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = 0;
        int measureHeight = 0;
        int tempw = MeasureSpec.getSize(widthMeasureSpec);
        int tmeph = MeasureSpec.getSize(heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);

        int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpaceMode = MeasureSpec.getMode(widthMeasureSpec);

        int heihtSpaceSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpaceMode = MeasureSpec.getMode(heightMeasureSpec);

        final int childCount = getChildCount();
        if(childCount == 0){
            setMeasuredDimension(0,0);
        }else {
            final View childView = getChildAt(0);
            measureWidth = childView.getMeasuredWidth() * childCount;
            measureHeight = childView.getMeasuredHeight();
            setMeasuredDimension(measureWidth,measureHeight);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childLeft = 0;
        final int childCount = getChildCount();
        for (int i = 0;i<childCount;i++){
            final View childView = getChildAt(i);
            if(childView.getVisibility() != View.GONE){
                final int childWidth = childView.getMeasuredWidth();
                this.mChildWidth = childWidth;
                childView.layout(childLeft,0,childWidth + childLeft,childView.getMeasuredHeight());
                childLeft += childWidth;
            }
        }
    }

    private void smoothScrollBy(int dx, int dy) {
        mScroller.startScroll(getScrollX(), 0, dx, 0, 500);
        invalidate();
    }

    @Override
    public void computeScroll() {
        if(mScroller.computeScrollOffset()){
            scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
            postInvalidate();
        }
    }
}
